package com.wei.spring.web.user.exception;

import com.wei.spring.web.user.model.dto.BaseCodeEnum;

/**
 * 类的详细说明
 * 如果继承某个接口{@link StateContext}，提供一个链接，方便使用
 * <p>
 * 如果是过期的接口，那么请尽量提供用于替换的类的链接地址{@link StateContext}
 *
 * @param <S> 如果用到泛型，可以这样注释
 * @param <E> 如果用到泛型，可以这样注释
 * @author buhuan.wang
 * @since 2020/12/21
 */
public class BusinessException extends RuntimeException {
    private static final long serialVersionUID = -1L;

    protected BaseCodeEnum respCode;
    protected String message = "";

    public BusinessException(Throwable cause, BaseCodeEnum codeEnum, Object... parameters) {
        super("", cause);
        this.message = generateErrorMsg(codeEnum, parameters);
        this.respCode = codeEnum;
    }

    public BusinessException(BaseCodeEnum codeEnum, Object... parameters) {
        super("");
        this.message = generateErrorMsg(codeEnum, parameters);
        this.respCode = codeEnum;
    }

    private String generateErrorMsg(BaseCodeEnum codeEnum, Object... parameters) {
        if (parameters.length > 0) {
            return String.format(codeEnum.getMessage(), parameters);
        } else {
            return codeEnum.getMessage();
        }
    }

    public String getCode() {
        return respCode.getCode();
    }

    @Override
    public String getMessage() {
        return message;
    }

    @Override
    public String toString() {
        return "BusinessException [errorCode=" + respCode.getCode() + ", errorMsg=" + message + "]";
    }
}

